import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import '../models/api_response_model.dart';

/// HTTP服务类
/// 负责处理所有网络请求，包括GET、POST、文件上传等
class HttpService {
  static const String _baseUrl = 'https://www.autorepairehelper.cn'; // 原项目API地址
  static const Duration _timeout = Duration(seconds: 30);
  
  static HttpService? _instance;
  static HttpService get instance {
    _instance ??= HttpService._();
    return _instance!;
  }
  
  HttpService._();
  
  /// 获取完整的请求头
  Future<Map<String, String>> _getHeaders() async {
    final prefs = await SharedPreferences.getInstance();
    final token = prefs.getString('user_token') ?? '';
    
    return {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Accept': 'application/json',
      if (token.isNotEmpty) 'Authorization': 'Bearer $token',
    };
  }
  
  /// 处理响应数据
  ApiResponse<T> _handleResponse<T>(http.Response response, T Function(dynamic)? fromJsonT) {
    try {
      final data = json.decode(response.body);
      final apiCode = data['code']?.toString();
      final isSuccess = apiCode == '1'; // API返回code为"1"表示成功
      
      // 获取原始数据
      final rawData = data['ret'] ?? data['data'];
      
      // 如果有转换函数，使用它来转换数据
      T? transformedData;
      if (fromJsonT != null && rawData != null) {
        try {
          transformedData = fromJsonT(rawData);
        } catch (e) {
          print('数据转换失败: $e');
          return ApiResponse<T>(
            success: false,
            code: 'TRANSFORM_ERROR',
            message: '数据转换失败: $e',
            data: null,
            statusCode: response.statusCode,
          );
        }
      } else {
        transformedData = rawData as T?;
      }
      
      return ApiResponse<T>(
        success: isSuccess,
        code: apiCode ?? response.statusCode.toString(),
        message: data['msg'] ?? data['message'] ?? '',
        data: transformedData,
        statusCode: response.statusCode,
      );
    } catch (e) {
      return ApiResponse<T>(
        success: false,
        code: 'PARSE_ERROR',
        message: '数据解析失败: $e',
        data: null,
        statusCode: response.statusCode,
      );
    }
  }
  
  /// GET请求
  Future<ApiResponse<T>> get<T>(String endpoint, {Map<String, dynamic>? params, T Function(dynamic)? fromJsonT}) async {
    try {
      final uri = Uri.parse('$_baseUrl$endpoint');
      final uriWithParams = params != null 
          ? uri.replace(queryParameters: params.map((k, v) => MapEntry(k, v.toString())))
          : uri;
      
      final response = await http.get(
        uriWithParams,
        headers: await _getHeaders(),
      ).timeout(_timeout);
      
      return _handleResponse<T>(response, fromJsonT);
    } catch (e) {
      return ApiResponse<T>(
        success: false,
        code: 'NETWORK_ERROR',
        message: '网络请求失败: $e',
        data: null,
        statusCode: 0,
      );
    }
  }
  
  /// POST请求
  Future<ApiResponse<T>> post<T>(String endpoint, {Map<String, dynamic>? body, T Function(dynamic)? fromJsonT}) async {
    try {
      final uri = Uri.parse('$_baseUrl$endpoint');
      final headers = await _getHeaders();
      
      // 将body转换为表单数据格式
      String requestBody = '';
      if (body != null) {
        requestBody = body.entries
            .map((e) => '${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value.toString())}')
            .join('&');
      }
      
      // 添加调试日志
      print('=== HTTP POST 请求调试信息 ===');
      print('URL: $uri');
      print('Headers: $headers');
      print('Body: $requestBody');
      
      final response = await http.post(
        uri,
        headers: headers,
        body: requestBody,
      ).timeout(_timeout);
      
      print('Response Status: ${response.statusCode}');
      print('Response Body: ${response.body}');
      print('=== 调试信息结束 ===');
      
      return _handleResponse<T>(response, fromJsonT);
    } catch (e) {
      print('HTTP请求异常: $e');
      return ApiResponse<T>(
        success: false,
        code: 'NETWORK_ERROR',
        message: '网络请求失败: $e',
        data: null,
        statusCode: 0,
      );
    }
  }
  
  /// 文件上传
  Future<ApiResponse<T>> uploadFile<T>(
    String endpoint, {
    required String filePath,
    required String fileName,
    Map<String, dynamic>? fields,
    T Function(dynamic)? fromJsonT,
  }) async {
    try {
      final uri = Uri.parse('$_baseUrl$endpoint');
      final request = http.MultipartRequest('POST', uri);
      
      // 添加文件
      request.files.add(await http.MultipartFile.fromPath('file', filePath, filename: fileName));
      
      // 添加其他字段
      if (fields != null) {
        fields.forEach((key, value) {
          request.fields[key] = value.toString();
        });
      }
      
      // 添加请求头
      final headers = await _getHeaders();
      request.headers.addAll(headers);
      
      final streamedResponse = await request.send().timeout(_timeout);
      final response = await http.Response.fromStream(streamedResponse);
      
      return _handleResponse<T>(response, fromJsonT);
    } catch (e) {
      return ApiResponse<T>(
        success: false,
        code: 'UPLOAD_ERROR',
        message: '文件上传失败: $e',
        data: null,
        statusCode: 0,
      );
    }
  }
}
